package com.bawei.module_main.ui.splash

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.Gravity
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.getAttrValue
import com.bawei.lib_common.getUrlParams
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.lib_storage.mmkv.AppMMKV
import com.bawei.module_main.R
import com.bawei.module_main.databinding.ActivitySplashBinding
import com.bawei.module_main.dialog.MessageNoticeDialog
import com.tencent.bugly.crashreport.CrashReport
import com.umeng.commonsdk.UMConfigure
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author yaotianxue
 * @description 闪屏页面
 * @date 2025/5/26
 */
@AndroidEntryPoint
class SplashActivity :BaseActivity<SplashViewModel,ActivitySplashBinding>(){
    private val mViewModel:SplashViewModel by viewModels()
    companion object {
        //最大延迟
        private const val SPLASH_MAX_DELAY: Long = 1_500
    }
    override val mLayoutResId: Int
        get() = R.layout.activity_splash

    private val mHandler by lazy {
        object:Handler(Looper.getMainLooper()){
            override fun handleMessage(msg: Message) {
                if (mViewModel.mAppStartAdInfo?.imageUrl.isNullOrEmpty()){
                    if (AppMMKV.needGuide){
                        toGuide()
                    }else{
                        toMain()
                    }
                }else{
                    toAd()
                }
            }
        }
    }
    //初始化结束后操作
    private var actionAfterInitFinished: (() -> Unit)? = null

    override fun initData() {
        //1:获得广告数据
        mViewModel.adList()
        //2:处理通知栏点击事件打开app
        //3:处理隐示跳转打开app
        val queryString = intent.data?.query
        if (!queryString.isNullOrBlank()) {
            val params = getUrlParams(queryString)
            val type = params["type"].toString().toInt()
            val id = params["id"]
            if (!isTaskRoot) {
                //App在后台:之前已经初始化
                handleLaunchAppParams(type, id.toString())
            } else {
                //app正在执行，初始化完毕稍后处理
                actionAfterInitFinished = {
                    handleLaunchAppParams(type, id.toString())
                }
            }
        }



        //4:弹出对话框
        if (!AppMMKV.splashAgreement){
            val colorMain = getAttrValue(this, com.bawei.lib_common.R.attr.colorTheme)
            val userAgreement = "《用户协议》"
            val privacyPolicy = "《隐私条款》"
            val content =
                "宗申骑士俱乐部非常尊重用户个人的信息保护，我们依据最新的监管要求特向您说明如下：\n1.在使用 APP过程中，我们有可能会收集、使用设备标识信息用于推送车辆提醒消息。\n2.我们会一直采取严格的安全技术保护您的个人信息安全。\n3.未经您的同意，我们不会以协议约定之外的形式和渠道获取、共享或使用您的个人信息。\n您可通过阅读完整的${userAgreement}和${privacyPolicy}来了解详细信息。请您充分阅读并理解以上协议，点击同意按钮，即表示您已同意上述协议及以上约定。"
            val spannableStringBuilder = SpannableStringBuilder(content)
            val userAgreementStart = content.indexOf(userAgreement)
            val userAgreementEnd = userAgreementStart + userAgreement.length
            val privacyPolicyStart = content.indexOf(privacyPolicy)
            val privacyPolicyEnd = privacyPolicyStart + privacyPolicy.length

            spannableStringBuilder.setSpan(object : ClickableSpan() {
                override fun onClick(p0: View) {
//                    CommonWebActivity.jumpUserAgreement()
                    showToast("点击了用户")
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(this@SplashActivity, colorMain)
                    ds.isUnderlineText = false
                }

            }, userAgreementStart, userAgreementEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)

            spannableStringBuilder.setSpan(object : ClickableSpan() {
                override fun onClick(p0: View) {
//                    CommonWebActivity.jumpPrivacyAgreement()
                    showToast("点击了隐私")
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(this@SplashActivity, colorMain)
                    ds.isUnderlineText = false
                }

            }, privacyPolicyStart, privacyPolicyEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            MessageNoticeDialog(
                title = "温馨提示",
                message = spannableStringBuilder,
                alignment = Gravity.START,
                onConfirmClick = {
                    AppMMKV.splashAgreement = true
                    mHandler.sendEmptyMessageDelayed(2,SPLASH_MAX_DELAY)
                    //第一次打卡：正式初始化
                    UMConfigure.init(this,"67170cee80464b33f6e18739","channel", UMConfigure.DEVICE_TYPE_PHONE,null)
                    CrashReport.initCrashReport(getApplicationContext(), "c0befbb921", true);
                                 },
                onCancelClick = {
                    finish()
                },
                confirmText = "同意",
                cancelText = "不同意",
                cancelable = false
            ).show(supportFragmentManager)

        }else{
            mHandler.sendEmptyMessageDelayed(2,SPLASH_MAX_DELAY)
        }
    }
    //处理h5唤醒App 1:首页(不用传id) 2:活动详情 3:动态详情 4:帖子 5:文章 6:指南
    private fun handleLaunchAppParams(type: Int?, id: String?) {
        when (type) {
            1 -> {
                //启动App do nothing
            }

            2 -> {
                if (id.isNullOrBlank()) {
                    ToastUtils.showShort(this, "活动信息有误")
                    return
                }
               // ClubActDetailActivity.jumpWithId(actId = id)
            }

            3 -> {
                if (id.isNullOrBlank()) {
                    ToastUtils.showShort(this, "动态信息有误")
                    return
                }
             //   TimelineDetailActivity.jump(dynamicId = id)
            }

            4 -> {
                if (id.isNullOrBlank()) {
                    ToastUtils.showShort(this, "帖子信息有误")
                    return
                }
           //     PostDetailsActivity.jump(postId = id)
            }

            5 -> {
                if (id.isNullOrBlank()) {
                    ToastUtils.showShort(this, "文章信息有误")
                    return
                }
            //    ArticleDetailsActivity.jump(articleId = id)
            }

            6 -> {
                if (id.isNullOrBlank()) {
                    ToastUtils.showShort(this, "指南信息有误")
                    return
                }
            //    GuideDetailsActivity.jump(guideId = id)
            }

            7 -> {
                //TODO 跳转咨询分享
            }

            8 -> {
                //路线分享
                if (id.isNullOrBlank()) {
                    ToastUtils.showShort(this, "路线信息有误")
                    return
                }
             //   RouteDetailsActivity.jump(routeId = id)
            }

            9 -> {
                //TODO 跳转知识库分享
            }

            10 -> {
                //TODO 跳转俱乐部详情
            }

            11 -> {
                //TODO 调整骑行组队
            }
        }
    }

    fun toAd(){
        ARouter.getInstance().build(Router.Ui.AdActivity)
            .withSerializable("mAdModel",mViewModel.mAppStartAdInfo)
            .navigation()
        actionAfterInitFinished?.invoke()
        finish()
    }

    fun toGuide(){
        ARouter.getInstance().build(Router.Ui.GuideActivity).navigation()
        actionAfterInitFinished?.invoke()
        finish()
    }

    fun toMain(){
        ARouter.getInstance().build(Router.Ui.MainActivity).navigation()
        actionAfterInitFinished?.invoke()
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        mHandler.removeCallbacksAndMessages(null) //防止内存泄漏
        actionAfterInitFinished = null

    }



}